﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;
using NVelocity.Context;
using LearnNet.Common;
using LearnNet.CodeHelper;
using System.IO;
using System.Xml;
using System.Threading;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Document;
namespace SQLTools
{
    public partial class NVelocityTools : Form
    {
        private NVelocityHelper nvHelper = null; //生成模板类
        LearnNet.IDBO.IDbScriptBuilder dsb;
        LearnNet.IDBO.IDbObject dbobj;
        LearnNet.CmConfig.DbSettings dbset;//服务器配置
        string DbName = "master";
        Thread mythread;
        protected List<TableInfo> tableInfos = null;

        public NVelocityTools()
        {
            InitializeComponent();
        }

        public NVelocityTools(string longservername, string dbname)
        {
            InitializeComponent();
            DbName = dbname;
            dbset = LearnNet.CmConfig.DbConfig.GetSetting(longservername);
            dbobj = LearnNet.DBFactory.DBOMaker.CreateDbObj(dbset.DbType);
            dbobj.DbConnectStr = dbset.ConnectStr;
            //cb = new LearnNet.CodeBuild.CodeBuilders(dbobj);
            dsb = LearnNet.DBFactory.DBOMaker.CreateScript(dbset.DbType);// ObjHelper.CreatDsb(longservername);
            tlsCmboxTables.Items.Clear();
            tlsCmboxTables.Items.Add("全部");
            List<string> tableNames = dbobj.GetTables(dbname);
            foreach (string tableName in tableNames)
            {
                tlsCmboxTables.Items.Add(tableName);
            }
            tlsCmboxTables.SelectedIndex = 0;
            tlsCmboxSyntax.SelectedIndex = 0;
            //this.lblServer.Text = dbset.Server;
        }
        public static System.Text.Encoding GetType(string FILE_NAME)
        {
            FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
            System.Text.Encoding r = GetType(fs);
            fs.Close();
            return r;
        }
        public static System.Text.Encoding GetType(FileStream fs)
        {
            /*byte[] Unicode=new byte[]{0xFF,0xFE};  
            byte[] UnicodeBIG=new byte[]{0xFE,0xFF};  
            byte[] UTF8=new byte[]{0xEF,0xBB,0xBF};*/

            BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
            byte[] ss = r.ReadBytes(3);
            r.Close();
            //编码类型 Coding=编码类型.ASCII;   
            if (ss[0] >= 0xEF)
            {
                if (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF)
                {
                    return System.Text.Encoding.UTF8;
                }
                else if (ss[0] == 0xFE && ss[1] == 0xFF)
                {
                    return System.Text.Encoding.BigEndianUnicode;
                }
                else if (ss[0] == 0xFF && ss[1] == 0xFE)
                {
                    return System.Text.Encoding.Unicode;
                }
                else
                {
                    return System.Text.Encoding.Default;
                }
            }
            else
            {
                return System.Text.Encoding.Default;
            }
        }   
        private void toolBtn_CreatCode_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            
            openFileDialog.Filter = "文本文件|*.*|htm文件|*.htm|html文件|*.html|txt文件|*.txt|所有文件|*.*";
            openFileDialog.RestoreDirectory = false;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
               string fName = openFileDialog.FileName;
               StreamReader strmreader = new StreamReader(fName, GetType(fName));
               ltptbSource.Text= strmreader.ReadToEnd();
               strmreader.Dispose();
               
            }  
        }

        private void ltptbSource_DragDrop(object sender, DragEventArgs e)
        {
            string draPath;
            try
            {
                draPath= ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
               ltptbSource.Text= File.OpenText(draPath).ToString();
            }
            catch (Exception ex){
                MessageBox.Show("拖动加载文件错误" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void NVelocityTools_DragDrop(object sender, DragEventArgs e)
        {
            string draPath;
            try
            {
                draPath = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                ltptbSource.Text = File.OpenText(draPath).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("拖动加载文件错误" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void toolBtn_Run_Click(object sender, EventArgs e)
        {
            if (ltptbSource.Text == "")
            {
                MessageBox.Show("模板内容不能为空");
                return;
            }
            TableInfo tableInfo = null;
            
          
            if (tlsCmboxTables.Items[tlsCmboxTables.SelectedIndex].ToString() == "全部")
            {
                tableInfos = dbobj.GetTablesInfo(DbName);
                for (int i = 0; i < tableInfos.Count; i++)
                {

                    tableInfos[i].ColumnInfos = dbobj.GetColumnList(DbName, tableInfos[i].TabName);

                }
            }
            else
            {
                tableInfos = new List<TableInfo>();
                tableInfos.Add(dbobj.GetTablesInfo(DbName, tlsCmboxTables.Items[tlsCmboxTables.SelectedIndex].ToString()));
                for (int i = 0; i < tableInfos.Count; i++)
                {
                    if(tableInfos[i]!=null)
                    tableInfos[i].ColumnInfos = dbobj.GetColumnList(DbName, tableInfos[i].TabName);

                }
            }
            Dictionary<string, string> dix = new Dictionary<string, string>();
            
            nvHelper = new NVelocityHelper("",false);
            nvHelper.SetLoaderCache(false, 0);
            nvHelper.RemoveAll();
            nvHelper.Put("TableInfos", tableInfos);
            try
            {
                ltbtbResult.Text = nvHelper.DisplayFromString(ltptbSource.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region 文本框按钮按下事件
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ltptbSource_KeyPressEvent(object sender, KeyEventArgs e)
        {
            string keyString = e.ToString();
            string line = ltptbSource.ActiveTextAreaControl.Caret.Line.ToString();
            string col = ltptbSource.ActiveTextAreaControl.Caret.Column.ToString();
            //((MainForm)MdiParentForm).SetPandelPositionInfo(line, col);

            if (e.Alt == true && e.KeyValue == 88)
            {
                e.Handled = false;
               
                return;
            }
            if (e.KeyCode == Keys.Down)
            {
                //lstv_Commands.Focus();
            }
            if (e.KeyCode == Keys.F11)
            {
                if (ltptbSource.Dock == DockStyle.Top)
                {
                    ltptbSource.Dock = DockStyle.Fill;
                    ltbtbResult.Visible = false;
                    ToolbarMain.Visible = false;
                }
                else
                {
                    ltptbSource.Dock = DockStyle.Top;
                    ltbtbResult.Visible = true;
                    ToolbarMain.Visible = true;
                }
            }
            if (e.KeyCode == Keys.F5)
            {
               
            }

            if (((Control.ModifierKeys & Keys.Control) == Keys.Control) && e.KeyValue == 32
                || e.KeyValue == 190)
            {
                if (e.KeyValue == 190)
                {
                    //ApplyProperty();
                }
                else
                {
                    e.Handled = true;
                    //ComplementWord();
                }
            }
            if (((Control.ModifierKeys & Keys.Control) == Keys.Control) && e.KeyValue == 67 || e.KeyValue == 99)
            {
                //ToggleComment();
            }
        }
        private void ltbtbResult_KeyPressEvent(object sender, KeyEventArgs e)
        {
            string keyString = e.ToString();
            string line = ltbtbResult.ActiveTextAreaControl.Caret.Line.ToString();
            string col = ltbtbResult.ActiveTextAreaControl.Caret.Column.ToString();
            //((MainForm)MdiParentForm).SetPandelPositionInfo(line, col);

            if (e.Alt == true && e.KeyValue == 88)
            {
                e.Handled = false;

                return;
            }
            if (e.KeyCode == Keys.Down)
            {
                //lstv_Commands.Focus();
            }
            //if (e.KeyCode == Keys.F11)
            //{
            //    if (ltbtbResult.Dock == DockStyle.Top)
            //    {
            //        ltbtbResult.Dock = DockStyle.Fill;
            //        ltbtbResult.Dock = DockStyle.None;
            //    }
            //    else
            //    {
            //        ltbtbResult.Dock = DockStyle.None;
            //        ltbtbResult.Dock = DockStyle.Top;
            //    }
            //}
            if (e.KeyCode == Keys.F5)
            {

            }

            if (((Control.ModifierKeys & Keys.Control) == Keys.Control) && e.KeyValue == 32
                || e.KeyValue == 190)
            {
                if (e.KeyValue == 190)
                {
                    //ApplyProperty();
                }
                else
                {
                    e.Handled = true;
                    //ComplementWord();
                }
            }
            if (((Control.ModifierKeys & Keys.Control) == Keys.Control) && e.KeyValue == 67 || e.KeyValue == 99)
            {
                //ToggleComment();
            }
        }
        #endregion 



        private void tlsCmboxSyntax_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tlsCmboxSyntax.Items[tlsCmboxSyntax.SelectedIndex].ToString() != "")
            {
                this.ltbtbResult.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy(tlsCmboxSyntax.Items[tlsCmboxSyntax.SelectedIndex].ToString());
                this.ltptbSource.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy(tlsCmboxSyntax.Items[tlsCmboxSyntax.SelectedIndex].ToString());
            }
        }

        private void toolStripLabel1_Click(object sender, EventArgs e)
        {

        }

      
  
    }
}
